package org.fastsyncer.rest.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.CommonConstant;
import org.fastsyncer.common.constant.ThirdpartyConstant;
import org.fastsyncer.common.util.ApplicationUtil;
import org.fastsyncer.common.util.SHA1Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 管理登录session API工具类
 * <p>1.写入票据 2.删除票据 3.验证票据</p>
 * 
 * @ClassName: Ticket
 * @author AE86
 * @date: 2017年9月5日 上午11:15:27
 */
public class Ticket {

    private static final Logger logger = LoggerFactory.getLogger(Ticket.class);

    /**
     * 会话过期时间标示
     */
    public static final String SESSION_TIMEOUT = "session_timeout";

    /**
     * 获取票据标识 ticket
     * 
     * @Title: getTicket
     * @Description: 获取写入浏览器的票据标识
     * @return: String 票据标识
     */
    private static String getTicket() {
        return ApplicationUtil.getKey(CommonConstant.CONFIG_INTERCEPTOR_TICKET);
    }

    /**
     * 验证用户口令,并设置票据信息
     * 
     * @Title: createTicket
     * @Description: 验证用户口令,并设置票据信息
     * @param request
     * @param response
     * @param username
     *            帐号
     * @param userpwd
     *            密码
     * @throws IllegalAccessError
     * @return: void
     * @throws Exception 
     */
    public static void createTicket(HttpServletRequest request, HttpServletResponse response, String username, String userpwd) throws Exception {
        // 如果认证失败，直接返回null
        String acc = ApplicationUtil.getKey(CommonConstant.CONFIG_ADMIN_ACCOUNT);
        String pwd = ApplicationUtil.getKey(CommonConstant.CONFIG_ADMIN_PWD);
        // 加密
        userpwd = SHA1Util.b64_sha1(userpwd);
        if (!acc.equals(username) || !pwd.equals(userpwd)) {
            throw new IllegalArgumentException("Account or password error.");
        }
        createTicket(request, username);
    }

    /**
     * 设置票据信息
     * @param session
     */
    public static void createTicket(HttpServletRequest request, String username) {
        HttpSession session = request.getSession();
        session.setAttribute(Ticket.getTicket(), username);
        // 会话失效时间（秒）,默认30分钟
        Integer maxAge = 1800;
        try {
            maxAge = Integer.parseInt(ApplicationUtil.getKey(CommonConstant.CONFIG_INTERCEPTOR_SESSION_MAX_AGE));
        } catch (NumberFormatException e) {
        }
        session.setAttribute(Ticket.SESSION_TIMEOUT, (System.currentTimeMillis() + maxAge * 1000));
        logger.info("Get the ticket successfully!" + session.getId());
    }

    /**
     * 移除票据信息
     * @param request
     * @throws Exception
     */
    public static void removeTicket(HttpSession session) throws Exception {
        session.removeAttribute(Ticket.getTicket());
        session.removeAttribute(Ticket.SESSION_TIMEOUT);
        session.removeAttribute(ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_APP_APPID));
    }

    /**
     * 验证票据是否存在,是否过期.如果过期删除票据信息
     * @param request
     * @return 未通过false,通过true
     * @throws Exception
     */
    public static boolean validateTicket(HttpSession session) throws Exception {
        String sessionId = (String) session.getAttribute(Ticket.getTicket());
        // 是否存在票据信息
        if(StringUtils.isBlank(sessionId)){
            return false;
        }
        // 票据是否过期
        if(System.currentTimeMillis() > (Long) session.getAttribute(Ticket.SESSION_TIMEOUT)){
            // 已过期,移除票据信息
            removeTicket(session);
            return false;
        }
        return true;
    }

}
